package com.decoration.basic.controller;

import java.util.List;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.decoration.basic.BasicController;
import com.decoration.basic.controller.api.DecUserController;
import com.decoration.basic.entity.DecorationUser;
import com.decoration.basic.entity.JsonResult;
import com.decoration.basic.findCondition.DecUserFindCondition;
import com.decoration.basic.service.DecUserService;
import com.decoration.basic.util.Global;
import com.decoration.basic.util.MD5Util;
import com.decoration.basic.util.SessionSingleton;

@RestController
@RequestMapping("/admin")
public class LoginController extends BasicController {

	// 日志记录器
	private static final Logger log = LoggerFactory.getLogger(DecUserController.class);
	@Resource(name = "DecUserService")
	private DecUserService decUserService;

	@RequestMapping(value = "/user/login", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult doLogin(JsonResult jsonResult, HttpServletResponse response, HttpSession session,
			@RequestBody DecorationUser users, HttpServletRequest request) {
		if (users.getPerAccount() == null || "".equals(users.getPerAccount())) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("请输入登录账号!");
			return jsonResult;
		}
		if (users.getPerPasswd() == null || "".equals(users.getPerPasswd())) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("请输入登录密码!");
			return jsonResult;
		}

		log.info("传入用户参数信息为:"+JSON.toJSONString(users));
		// 查询该用户的数据是否存在
		DecorationUser user = decUserService.findByPhone(users.getPerAccount());
		if (user == null) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("账号或密码错误,请重试!");
			return jsonResult;
		}
		// 校验当前用户是否为管理员 / 渠道业务员
		if (user.getPerType() == Global.USER_MANAGER) {
			// 密码校验
			String loginPass = MD5Util.getMD5(user.getPerSalt(), users.getPerPasswd());
//			String loginPass = userPasswd;
			if (!loginPass.equals(user.getPerPasswd())) {
				jsonResult.setCode(JsonResult.FAILED_CODE);
				jsonResult.setMsg("账号或密码错误,请重试!");
				return jsonResult;
			}
			// 保存当前登录ip
//			user.setLoginIp(ComUtils.getIpAddress(request));
//			user.setLastLoginTime(new Date());
//			decUserService.update(user);
			// 判断账号是否已经登陆
			// SessionSingleton.getInstance().checkSession(user.getUserId(), session);
			// 保存当前用户信息
			session.setAttribute(Global.SESSION_USER_ID, user.getUserId());
			session.setAttribute(Global.SESSION_USER_NAME, user.getPerName());
			session.setAttribute(Global.SESSION_USER_ACCOUNT, user.getPerAccount());
			session.setAttribute(Global.SESSION_USER_TYPE, user.getPerType());
			// 保存已登录账号的session
			SessionSingleton.getInstance().putServiceSession(user.getUserId(), request.getSession());
			jsonResult.setCode(JsonResult.SUCCESS_CODE);
			jsonResult.setMsg("登录成功!");
			jsonResult.setData(user);
			return jsonResult;
		}
		jsonResult.setCode(JsonResult.FAILED_CODE);
		jsonResult.setMsg("暂无登陆权限,请更换账号后重试!");
		return jsonResult;
	}

	@RequestMapping(value = "/user/exit", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult doExit(JsonResult jsonResult, HttpServletResponse response, HttpSession session,
			@RequestBody DecorationUser users, HttpServletRequest request) {

//		if (users.getPerAccount() == null || "".equals(users.getPerAccount())) {
//			jsonResult.setCode(JsonResult.FAILED_CODE);
//			jsonResult.setMsg("退出账号不允许为空，请重新输入!");
//			return jsonResult;
//		}
//
//		// 查询该用户的数据是否存在
//		DecorationUser user = decUserService.findByPhone(users.getPerAccount());
//		if (user == null) {
//			jsonResult.setCode(JsonResult.FAILED_CODE);
//			jsonResult.setMsg("账号不存在,账号退出失败!");
//			return jsonResult;
//		}
		String userid = (String)request.getSession().getAttribute(Global.SESSION_USER_ID);
		// 判断账号是否已经登陆
		SessionSingleton.getInstance().removeServiceSession(userid, session);

		jsonResult.setCode(JsonResult.SUCCESS_CODE);
		jsonResult.setMsg("账号退出成功!");
		return jsonResult;
	}

	@RequestMapping(value = "/user/add", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult addUser(JsonResult jsonResult, @RequestBody DecorationUser user,HttpServletRequest request) {

		/*if (StringUtils.isBlank(user.getPerPasswd()) || StringUtils.isBlank(user.getPerAccount())) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("需要修改的用户/密码不存在,请重试!");
			return jsonResult;
		}*/
		log.info("后端新增用户信息开始");
		DecorationUser users = decUserService.findByPhone(user.getPerAccount());
		if (users != null) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("账号已存在,请重试!");
			return jsonResult;
		}
		// 生成8位随机数
		StringBuilder perSalt = new StringBuilder();
		Random random = new Random();
		// 随机生成数字，并添加到字符串
		for (int i = 0; i < 8; i++) {
			perSalt.append(random.nextInt(10));
		}
		String perPasswd = MD5Util.getMD5(perSalt.toString(), "123456");
		user.setPerPasswd(perPasswd);
		user.setPerSalt(perSalt.toString());
		Object userId = "";
		try {
			userId = request.getSession().getAttribute(Global.SESSION_USER_ID);
		} catch (Exception e) {
			log.error("获取会话中用户信息异常",e );
		}
		user.setCreateId(userId.toString());
		user.setUpdateId(userId.toString());
		//user.setCreateId();

		Boolean bSuc = decUserService.add(user);
		
		if (!bSuc) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("添加账号失败,请重试!");
			return jsonResult;
		}
		jsonResult.setCode(JsonResult.SUCCESS_CODE);
		jsonResult.setMsg("账号添加成功");
		return jsonResult;
	}

	@RequestMapping(value = "/user/update", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult updateUser(JsonResult jsonResult, @RequestBody DecorationUser user) {
		/*if (StringUtils.isBlank(user.getPerPasswd()) || StringUtils.isBlank(user.getUserId())) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("需要修改的用户/密码不存在,请重试!");
			return jsonResult;
		}*/

		if ( StringUtils.isBlank(user.getUserId())) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("需要修改的用户不存在,请重试!");
			return jsonResult;
		}

		Boolean bSuc = decUserService.update(user);
		if (bSuc == false) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("修改账号失败,请重试!");
			return jsonResult;
		}
		jsonResult.setCode(JsonResult.SUCCESS_CODE);
		jsonResult.setMsg("账号修改成功");
		return jsonResult;
	}

	@RequestMapping(value = "/user/del", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult delUser(JsonResult jsonResult, @RequestBody DecorationUser user) {
		if (null == user || "".equals(user)) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("需要删除的用户信息为空,请重试!");
			return jsonResult;
		}
		if (null == user.getUserId() || "".equals(user.getUserId())) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("需要删除的账号信息为空,请重试!");
			return jsonResult;
		}
		// 设置用户状态为不可用
		user.setPerVailed(1);
		Boolean bSuc = decUserService.update(user);
		if (bSuc == false) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("删除账号失败,请重试!");
			return jsonResult;
		}
		jsonResult.setCode(JsonResult.SUCCESS_CODE);
		jsonResult.setMsg("账号删除成功");
		return jsonResult;
	}

	@RequestMapping(value = "/user/list", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult getUserList(JsonResult jsonResult, @RequestBody DecUserFindCondition findCondition) {
		setPagerInfo(findCondition);
		List<DecorationUser> list = decUserService.getUserList(findCondition);
		// 时间格式化,清除原始时间,清除密码
		for (DecorationUser commission : list) {
			commission.setPerPasswd(null);
			commission.setPerSalt(null);
		}
		Integer count = null;
		try {
			count = decUserService.getUserSize(findCondition);
		} catch (Exception e) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setCount(0);
			jsonResult.setMsg("操作数据库失败!");
			return jsonResult;
		}
		jsonResult.setCode(JsonResult.SUCCESS_CODE);
		jsonResult.setCount(count);
		jsonResult.setData(list);
		return jsonResult;
	}

	// 根据id获取当前登录用户信息
	@RequestMapping(value = "/user/{userId}", method = RequestMethod.GET)
	@ResponseBody
	public JsonResult getUser(JsonResult jsonResult, @PathVariable String userId) {

		DecorationUser user = decUserService.findById(userId);
		if (user == null) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("无此用户信息");
			return jsonResult;
		}
		user.setPerPasswd(null);
		jsonResult.setCode(JsonResult.SUCCESS_CODE);
		jsonResult.setMsg("查询成功");
		jsonResult.setData(user);

		return jsonResult;
	}

}
